package services;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.axis2.context.MessageContext;

import model.Client;


public class CreditCardService 
{
	private static Statement stmt;
    private static Connection conn;
	
	public boolean makePayment(Client c, double v)
	{
		String sql = "";
		ResultSet rs;
		
		try
		{
			sql = "SELECT balance FROM creditCard WHERE cardID IN" +
				  "(SELECT creditCardNumber FROM client WHERE clientID = " + c.getClientId() + ")";
			rs = getStatement().executeQuery(sql);
			
			if (rs.next())
			{
				double balance = rs.getDouble("balance");
				
				if (balance >= v)
				{
					sql = "UPDATE creditCard SET balance = " + (balance-v) + " WHERE cardID = " + c.getCreditNumber();
					getStatement().execute(sql);
					
					return true;
				}
				else
					return false;
			}
		}
		catch (SQLException ex)
		{ ex.printStackTrace(); }
		catch (FileNotFoundException e) 
		{ e.printStackTrace(); }
		catch (IOException e) 
		{ e.printStackTrace(); }
		
		return false;
	}
		
		
	private static Statement getStatement() throws FileNotFoundException, IOException
	{
		if (stmt != null)
			return stmt;
		
		try 
		{
			MessageContext msg = MessageContext.getCurrentMessageContext();
			String url = (String)msg.getParameter("jdbc.url").getValue();
			String user = (String)msg.getParameter("jdbc.user").getValue();
			String password = (String)msg.getParameter("jdbc.pwd").getValue();
								
			// Properties properties = new Properties();
			// FileInputStream input = new FileInputStream("database.properties");
			// properties.load(input);
			// input.close();
									
			// String url = properties.getProperty("jdbc.url");
			// String user = properties.getProperty("jdbc.user");
			// String password = properties.getProperty("jdbc.pwd");
	        
	        Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
		}
		catch (ClassNotFoundException ex) 
		{ System.out.println("Driver JDBC-ODBC n�o encontrado"); }
		catch (SQLException ex) 
		{ System.out.println("Erro: " + ex.getMessage()); }
		catch (Exception e) 
		{ System.out.println("Erro: " + e.getMessage()); }

	    return stmt;
	}
}
